using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using CaipuGuanliXitong.Models;
using System.Text.Json;
using System.Linq;

namespace CaipuGuanliXitong.Controllers;

public class DailyPurchaseController : Controller
{
    private readonly CookBookDbContext _context;

    public DailyPurchaseController(CookBookDbContext context)
    {
        _context = context;
    }

    // GET: DailyPurchase
    // 重定向到计算页面
    public IActionResult Index()
    {
        return RedirectToAction("Calculate");
    }

    // GET: DailyPurchase/Calculate
    // 显示采购清单计算页面
    public IActionResult Calculate(DateTime? date)
    {
        // 如果没有提供日期，则使用当前日期
        if (!date.HasValue)
        {
            date = DateTime.Now.Date;
        }

        ViewBag.Date = date.Value;
        
        // 创建空的采购清单用于初始显示
        var emptyPurchaseDto = new DailyPurchaseDto
        {
            Date = date.Value,
            BreakfastDetails = new List<DailyPurchaseDetailDto>(),
            LunchDetails = new List<DailyPurchaseDetailDto>(),
            DinnerDetails = new List<DailyPurchaseDetailDto>(),
            MenuRecipes = new List<MenuRecipeDto>(),
            BreakfastTotalAmount = 0,
            LunchTotalAmount = 0,
            DinnerTotalAmount = 0,
            TotalAmount = 0
        };
        
        return View(emptyPurchaseDto);
    }

    // POST: DailyPurchase/Calculate
    // 根据输入参数计算每日采购清单
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Calculate(
        DateTime date,
        int breakfastMale,
        int breakfastFemale,
        int lunchMale,
        int lunchFemale,
        int dinnerMale,
        int dinnerFemale)
    {
        // 获取指定日期是星期几，用于查询周菜单
        DayOfWeek dayOfWeek = date.DayOfWeek;
        int dayNumber = dayOfWeek switch
        {
            DayOfWeek.Monday => 1,
            DayOfWeek.Tuesday => 2,
            DayOfWeek.Wednesday => 3,
            DayOfWeek.Thursday => 4,
            DayOfWeek.Friday => 5,
            DayOfWeek.Saturday => 6,
            DayOfWeek.Sunday => 7,
            _ => 1
        };

        // 查找该日期所在周的开始日期（周一），用于查询该周的菜单
        DateTime weekStartDate = date.Date;
        while (weekStartDate.DayOfWeek != DayOfWeek.Monday)
        {
            weekStartDate = weekStartDate.AddDays(-1);
        }

        // 获取当天的所有菜单（包括早、中、晚餐，男、女）
        var dailyMenus = _context.WeeklyMenus.GetList(x => 
            x.WeekStartDate == weekStartDate && x.DayOfWeek == dayNumber && x.IsDeleted == false);

        // 创建采购清单详情容器，分别存储早、中、晚餐的采购清单
        var breakfastPurchaseDetails = new List<DailyPurchaseDetailDto>(); // 早餐采购
        var lunchPurchaseDetails = new List<DailyPurchaseDetailDto>();     // 午餐采购
        var dinnerPurchaseDetails = new List<DailyPurchaseDetailDto>();    // 晚餐采购

        // 定义餐别和对应的人数配置，便于循环处理
        var mealGenders = new[]
        {
            new { MealType = 1, MaleCount = breakfastMale, FemaleCount = breakfastFemale }, // 早餐
            new { MealType = 2, MaleCount = lunchMale, FemaleCount = lunchFemale },        // 午餐
            new { MealType = 3, MaleCount = dinnerMale, FemaleCount = dinnerFemale }       // 晚餐
        };

        // 遍历每餐每性别，根据菜单和人数计算所需食材
        foreach (var mealGender in mealGenders)
        {
            // 获取该餐别男性的菜单列表
            var maleMenus = dailyMenus.Where(x => 
                x.MealType == mealGender.MealType && x.Gender == 1 && x.IsDeleted == false).ToList();

            // 获取该餐别女性的菜单列表
            var femaleMenus = dailyMenus.Where(x => 
                x.MealType == mealGender.MealType && x.Gender == 2 && x.IsDeleted == false).ToList();

            // 根据餐别类型确定采购清单目标容器
            List<DailyPurchaseDetailDto> targetList = mealGender.MealType switch
            {
                1 => breakfastPurchaseDetails, // 早餐
                2 => lunchPurchaseDetails,     // 午餐
                3 => dinnerPurchaseDetails,    // 晚餐
                _ => breakfastPurchaseDetails
            };

            // 处理男性菜单：如果男性人数大于0且存在男性菜单，则添加对应食材到采购清单
            if (mealGender.MaleCount > 0)
            {
                foreach (var maleMenu in maleMenus)
                {
                    // 检查菜单是否存在且包含菜谱ID
                    if (maleMenu != null && !string.IsNullOrEmpty(maleMenu.CookBookIds))
                    {
                        // 解析菜谱ID列表
                        var cookBookIds = maleMenu.CookBookIds.Split(',').Select(int.Parse).ToList();
                        // 添加食材到采购清单
                        AddIngredientsToPurchase(targetList, cookBookIds, mealGender.MaleCount);
                    }
                }
            }

            // 处理女性菜单：如果女性人数大于0且存在女性菜单，则添加对应食材到采购清单
            if (mealGender.FemaleCount > 0)
            {
                foreach (var femaleMenu in femaleMenus)
                {
                    // 检查菜单是否存在且包含菜谱ID
                    if (femaleMenu != null && !string.IsNullOrEmpty(femaleMenu.CookBookIds))
                    {
                        // 解析菜谱ID列表
                        var cookBookIds = femaleMenu.CookBookIds.Split(',').Select(int.Parse).ToList();
                        // 添加食材到采购清单
                        AddIngredientsToPurchase(targetList, cookBookIds, mealGender.FemaleCount);
                    }
                }
            }
        }

        // 合并相同食材 - 早餐采购
        // 按食材ID分组，合并相同食材的数量和金额
        var mergedBreakfastDetails = breakfastPurchaseDetails
            .GroupBy(x => x.IngredientId)
            .Select(g => new DailyPurchaseDetailDto
            {
                IngredientId = g.First().IngredientId,
                IngredientName = g.First().IngredientName,
                IngredientUnit = g.First().IngredientUnit,
                Quantity = g.Sum(x => x.Quantity),
                Price = g.First().Price,
                TotalAmount = g.Sum(x => x.TotalAmount)
            })
            .OrderBy(x => x.IngredientName)
            .ToList();
            
        // 合并相同食材 - 午餐采购
        var mergedLunchDetails = lunchPurchaseDetails
            .GroupBy(x => x.IngredientId)
            .Select(g => new DailyPurchaseDetailDto
            {
                IngredientId = g.First().IngredientId,
                IngredientName = g.First().IngredientName,
                IngredientUnit = g.First().IngredientUnit,
                Quantity = g.Sum(x => x.Quantity),
                Price = g.First().Price,
                TotalAmount = g.Sum(x => x.TotalAmount)
            })
            .OrderBy(x => x.IngredientName)
            .ToList();
            
        // 合并相同食材 - 晚餐采购
        var mergedDinnerDetails = dinnerPurchaseDetails
            .GroupBy(x => x.IngredientId)
            .Select(g => new DailyPurchaseDetailDto
            {
                IngredientId = g.First().IngredientId,
                IngredientName = g.First().IngredientName,
                IngredientUnit = g.First().IngredientUnit,
                Quantity = g.Sum(x => x.Quantity),
                Price = g.First().Price,
                TotalAmount = g.Sum(x => x.TotalAmount)
            })
            .OrderBy(x => x.IngredientName)
            .ToList();

        // 计算各餐别和总金额
        decimal breakfastTotalAmount = mergedBreakfastDetails.Sum(x => x.TotalAmount);
        decimal lunchTotalAmount = mergedLunchDetails.Sum(x => x.TotalAmount);
        decimal dinnerTotalAmount = mergedDinnerDetails.Sum(x => x.TotalAmount);
        decimal totalAmount = breakfastTotalAmount + lunchTotalAmount + dinnerTotalAmount;

        // 获取当天的菜单菜谱信息，用于页面显示
        var menuRecipes = new List<MenuRecipeDto>();
        
        // 获取所有餐别的菜单
        var allMenus = dailyMenus.ToList();
        
        // 遍历所有菜单，生成菜谱信息
        foreach (var menu in allMenus)
        {
            // 根据餐别代码获取餐别名称
            string mealType = menu.MealType switch
            {
                1 => "早餐",
                2 => "午餐",
                3 => "晚餐",
                _ => "未知餐别"
            };
            
            // 根据性别代码获取性别名称
            string gender = menu.Gender switch
            {
                1 => "男性",
                2 => "女性",
                _ => "未知性别"
            };
            
            // 根据餐别和性别获取对应的人数
            int count = menu.MealType switch
            {
                1 => menu.Gender == 1 ? breakfastMale : breakfastFemale,
                2 => menu.Gender == 1 ? lunchMale : lunchFemale,
                3 => menu.Gender == 1 ? dinnerMale : dinnerFemale,
                _ => 0
            };
            
            // 如果菜单包含菜谱名称，则添加到菜谱信息列表中
            if (!string.IsNullOrEmpty(menu.CookBookNames))
            {
                menuRecipes.Add(new MenuRecipeDto
                {
                    MealType = mealType,
                    Gender = gender,
                    RecipeNames = menu.CookBookNames.Replace(",", "、"),
                    Count = count
                });
            }
        }

        // 创建DTO对象，用于传递给视图
        var dailyPurchaseDto = new DailyPurchaseDto
        {
            Date = date,
            BreakfastMaleCount = breakfastMale,
            BreakfastFemaleCount = breakfastFemale,
            LunchMaleCount = lunchMale,
            LunchFemaleCount = lunchFemale,
            DinnerMaleCount = dinnerMale,
            DinnerFemaleCount = dinnerFemale,
            BreakfastDetails = mergedBreakfastDetails,
            LunchDetails = mergedLunchDetails,
            DinnerDetails = mergedDinnerDetails,
            MenuRecipes = menuRecipes,
            BreakfastTotalAmount = breakfastTotalAmount,
            LunchTotalAmount = lunchTotalAmount,
            DinnerTotalAmount = dinnerTotalAmount,
            TotalAmount = totalAmount
        };

        ViewBag.Date = date;
        return View("Calculate", dailyPurchaseDto);
    }

    // 辅助方法：根据菜谱ID和人数添加食材到采购清单
    private void AddIngredientsToPurchase(List<DailyPurchaseDetailDto> purchaseDetails, List<int> cookBookIds, int count)
    {
        // 遍历所有菜谱ID
        foreach (var cookBookId in cookBookIds)
        {
            // 获取菜谱的食材列表
            var recipeIngredients = _context.RecipeIngredients.GetList(x => x.CookBookId == cookBookId && x.IsDeleted == false);
            
            // 添加调试信息：输出菜谱ID和食材数量
            System.Diagnostics.Debug.WriteLine($"Processing Recipe ID: {cookBookId}, Number of Ingredients: {recipeIngredients.Count}");
            
            // 遍历菜谱中的每种食材
            foreach (var recipeIngredient in recipeIngredients)
            {
                if (recipeIngredient == null)
                {
                    System.Diagnostics.Debug.WriteLine("发现空的食材条目");
                    continue;
                }

                // 从食材管理模块获取食材单价
                decimal ingredientPrice = GetIngredientPrice(recipeIngredient.IngredientId);
                
                // 获取食材单位
                string ingredientUnit = GetIngredientUnit(recipeIngredient.IngredientId);
                if (string.IsNullOrEmpty(ingredientUnit))
                {
                    System.Diagnostics.Debug.WriteLine($"无法获取食材单位: {recipeIngredient.IngredientName}");
                    continue;
                }

                // 获取食材单价
                decimal price = GetIngredientPrice(recipeIngredient.IngredientId);
                if (price <= 0)
                {
                    System.Diagnostics.Debug.WriteLine($"食材单价无效: {recipeIngredient.IngredientName}, 价格: {price}");
                    // 即使价格为0，也继续处理，因为可能是免费食材或者价格待定
                }

                // 添加详细调试信息：食材原始数据
                System.Diagnostics.Debug.WriteLine($"Ingredient ID: {recipeIngredient.IngredientId}, " +
                                                  $"Name: {recipeIngredient.IngredientName}, " +
                                                  $"Quantity per person: {recipeIngredient.Quantity}, " +
                                                  $"Unit: {ingredientUnit}, " +
                                                  $"Price: {price:F2}, " +
                                                  $"People Count: {count}");
                
                // 创建采购清单详情项
                var detail = new DailyPurchaseDetailDto
                {
                    IngredientId = recipeIngredient.IngredientId,
                    IngredientName = recipeIngredient.IngredientName,
                    IngredientUnit = ingredientUnit,
                    Quantity = recipeIngredient.Quantity * count,         // 计算所需数量
                    Price = price,                                        // 使用食材管理模块中的单价
                    TotalAmount = price * recipeIngredient.Quantity * count  // 计算总金额
                };
                
                // 添加详细调试信息：计算结果
                System.Diagnostics.Debug.WriteLine($"计算结果 - 食材: {detail.IngredientName}, " +
                                                  $"数量: {detail.Quantity:F3}, " +
                                                  $"单价: {detail.Price:F2}, " +
                                                  $"金额: {detail.TotalAmount:F2}");
                
                // 添加到采购清单中
                purchaseDetails.Add(detail);
            }
        }
    }

    // 辅助方法：获取食材单位
    private string GetIngredientUnit(int ingredientId)
    {
        var ingredient = _context.Ingredients.GetSingle(x => x.Id == ingredientId);
        return ingredient?.Unit ?? "";
    }
    
    // 辅助方法：获取食材单价
    private decimal GetIngredientPrice(int ingredientId)
    {
        var ingredient = _context.Ingredients.GetSingle(x => x.Id == ingredientId);
        return ingredient?.Price ?? 0;
    }

    // GET: DailyPurchase/ExportToExcel
    // 导出到Excel（暂未实现）
    public IActionResult ExportToExcel(DateTime date)
    {
        return RedirectToAction(nameof(Calculate), new { date = date });
    }
    
    // POST: DailyPurchase/Save
    // 保存采购清单
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Save(DailyPurchaseDto dailyPurchaseDto)
    {
        try
        {
            // 创建DailyPurchase实体
            var dailyPurchase = new DailyPurchase
            {
                Date = dailyPurchaseDto.Date,
                BreakfastMaleCount = dailyPurchaseDto.BreakfastMaleCount,
                BreakfastFemaleCount = dailyPurchaseDto.BreakfastFemaleCount,
                LunchMaleCount = dailyPurchaseDto.LunchMaleCount,
                LunchFemaleCount = dailyPurchaseDto.LunchFemaleCount,
                DinnerMaleCount = dailyPurchaseDto.DinnerMaleCount,
                DinnerFemaleCount = dailyPurchaseDto.DinnerFemaleCount,
                CreatedTime = DateTime.Now,
                UpdatedTime = DateTime.Now
            };
            
            // 保存DailyPurchase主表记录并获取插入后的实体（包含ID）
            var insertedPurchase = _context.DailyPurchases.InsertReturnEntity(dailyPurchase);
            
            // 保存早餐采购详情
            foreach (var detail in dailyPurchaseDto.BreakfastDetails)
            {
                var breakfastDetail = new DailyPurchaseDetail
                {
                    DailyPurchaseId = insertedPurchase.Id,
                    IngredientId = detail.IngredientId,
                    IngredientName = detail.IngredientName,
                    IngredientUnit = detail.IngredientUnit,
                    Quantity = detail.Quantity,
                    Price = detail.Price,
                    TotalAmount = detail.TotalAmount,
                    CreatedTime = DateTime.Now,
                    UpdatedTime = DateTime.Now
                };
                _context.DailyPurchaseDetails.Insert(breakfastDetail);
            }
            
            // 保存午餐采购详情
            foreach (var detail in dailyPurchaseDto.LunchDetails)
            {
                var lunchDetail = new DailyPurchaseDetail
                {
                    DailyPurchaseId = insertedPurchase.Id,
                    IngredientId = detail.IngredientId,
                    IngredientName = detail.IngredientName,
                    IngredientUnit = detail.IngredientUnit,
                    Quantity = detail.Quantity,
                    Price = detail.Price,
                    TotalAmount = detail.TotalAmount,
                    CreatedTime = DateTime.Now,
                    UpdatedTime = DateTime.Now
                };
                _context.DailyPurchaseDetails.Insert(lunchDetail);
            }
            
            // 保存晚餐采购详情
            foreach (var detail in dailyPurchaseDto.DinnerDetails)
            {
                var dinnerDetail = new DailyPurchaseDetail
                {
                    DailyPurchaseId = insertedPurchase.Id,
                    IngredientId = detail.IngredientId,
                    IngredientName = detail.IngredientName,
                    IngredientUnit = detail.IngredientUnit,
                    Quantity = detail.Quantity,
                    Price = detail.Price,
                    TotalAmount = detail.TotalAmount,
                    CreatedTime = DateTime.Now,
                    UpdatedTime = DateTime.Now
                };
                _context.DailyPurchaseDetails.Insert(dinnerDetail);
            }
            
            // 返回成功结果
            TempData["SuccessMessage"] = "采购清单已成功保存！";
            return RedirectToAction(nameof(Calculate), new { date = dailyPurchaseDto.Date });
        }
        catch (Exception ex)
        {
            TempData["ErrorMessage"] = "保存采购清单时出错: " + ex.Message;
            return RedirectToAction(nameof(Calculate), new { date = dailyPurchaseDto.Date });
        }
    }
}